package com.cskaoyan.aspect;

import com.cskaoyan.bean.MemoryBean;
import com.cskaoyan.bean.po.wxorder.MarketFootprint;
import com.cskaoyan.bean.po.wxorder.MarketFootprintExample;
import com.cskaoyan.mapper.wxorder.MarketFootprintMapper;
import com.cskaoyan.util.common.Constant;
import com.cskaoyan.util.common.DateUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;

/**
 * @author Zhang Tao
 * @version 1.0.0
 * @description
 * @date since 2022-07-21 21:38
 */
@Component
@Aspect
public class CustomFootprintAspect {

    @Autowired
    MarketFootprintMapper marketFootprintMapper;
    @Autowired
    MemoryBean memoryBean;

    @Pointcut("@annotation(com.cskaoyan.aspect.AnnoFootprint)")
    public void myPointcut() {


    }


    @Around("myPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = joinPoint.proceed();
        Object[] args = joinPoint.getArgs();
        String token = (String) args[0];
        Integer goodsId = (Integer) args[1];
        MarketFootprint record = new MarketFootprint();
        record.setGoodsId(goodsId);
        record.setAddTime(DateUtils.time());
        record.setUpdateTime(DateUtils.time());

        // 根据goodsId查找到足迹信息
        MarketFootprintExample example = new MarketFootprintExample();
        MarketFootprintExample.Criteria criteria = example.createCriteria();
        criteria.andGoodsIdEqualTo(goodsId);

        Integer userId = memoryBean.tokenAndUserId.get(token);

        // 如果已经登录
        if (userId != null) {
            record.setUserId(userId);

            criteria.andUserIdEqualTo(userId);
        }

        // 查找userId和goodsId相同的历史记录
        List<MarketFootprint> marketFootprintList = marketFootprintMapper.selectByExample(example);

        // 判断足迹信息的大小 限制后续足迹的重复次数
        if (marketFootprintList.size() < Constant.MAX_FOOTPRINT_SIZE) {
            marketFootprintMapper.insertSelective(record);
            return proceed;

        }
        // 到这历史足迹大于等于设定值 判断出时间最旧的并更新添加日期
        Date oldest = marketFootprintList.get(0).getAddTime();
        Integer id = marketFootprintList.get(0).getId();
        for (int i = 1; i < marketFootprintList.size(); i++) {
            // 小于零则前面时间大
            MarketFootprint marketFootprint = marketFootprintList.get(i);
            Date addTime = marketFootprint.getAddTime();
            Integer footId = marketFootprint.getId();
            if (addTime.compareTo(oldest) < 0) {
                oldest = addTime;
                id = footId;
            }
        }

        // 更新最旧的历史足迹
        record.setId(id);
        marketFootprintMapper.updateByPrimaryKeySelective(record);
        return proceed;
    }
}

